// pages/member/rankingListSecond/rankingListSecond.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    language: '',
    // 登陆会员冻结爱心值
    froze: 0,
    //爱心值自定义名称
    love_name: "",
    // 转让开关是否开启
    transfer_status: false,
    // 转让开关是否开启
    trading_status: false,
    //待用爱心值
    recharge: 0,
    //是否可提现
    withdraw_status: false,
    //是否可以
    recharge_status: false,
    title: '', //标题,
    show: false, //控制爱心值出售的显示
    //爱心转账值
    sell_value: "",
    //爱心会员ID
    sell_id: "",
    // 转让手续费比率
    poundage: 0,
    trading_limit: 0,
    trading_fold: 0,
    usable: 0, // 登陆会员可用爱心值
    ios_virtual_pay: false,
    speed_pool_enable: 0, //加速池开关

    froze_name: '', //冻结兑换值
    usable_name: '', //兑换值激活

    redpack_enable: false, // 开启爱心值红包
    activation_record: false, // 激活记录是否开启

    withdrawData: {
      day: 0,
      disable: 0,
      day_msg: "",
      language: "提现"
    }, //* 优化任务：#71673

    love_cycle_reward: 'disabled',
    transfer_point_status: '',
    pointKey: '',

    // 御为民-爱心值队列
    love_queue: "",
    credit_validity_at: 0,
    love_queue_length: 0,
    change_integral:{},
    integral:"消费积分",
    point:'积分',
    // 是否显示爱心值转换积分
    transformation_point:false,
    active_froze:"", //冻结爱心值激活
    show_usable: false, //是否显示可用爱心值
    transferName:'',
    // 转换冻结爱心值
    usable_love_to_freeze:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 推广页限制
    this.checkrouter();
    // 爱心值出售的方法调用
    // this.getUsable();
    try {
      var value = wx.getStorageSync('ios_virtual_pay');
      if (value) {
        this.setData({
          ios_virtual_pay: value
        });
      }
    } catch (e) {
      console.log(e);
    }
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(',');
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split('=');
          if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          }
        }
      }
    }
  },
  checkrouter() {
    try {
      // 推广中心是否开启该功能，没开启跳转到指定路径
      let basic_info = wx.getStorageSync("yz_basic_info");
      let stop_info = basic_info.popularize_page.mini.vue_route;
      for (let i = 0; i < stop_info.length; i++) {
        if (stop_info[i] == 'love_index') {
          console.log(basic_info.popularize_page.mini.mini_url + "跳转的路径");

          wx.showToast({
            title: '未开启推广权限',
            duration: 2000,
            icon: 'none',
            success: function () {
              setTimeout(() => {
                wx.redirectTo({
                  url: basic_info.popularize_page.mini.mini_url,
                });
              }, 1000);
            }
          });
          return;
        }
      }
    } catch (e) {
      console.log(e);
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getyz_basic_info();
    this.getBalance();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getyz_basic_info() {
    try {
      let basic_info = wx.getStorageSync("yz_basic_info");
      if (basic_info) {
        console.log(basic_info);
        this.setData({
          integral: basic_info.integral,
          point : wx.getStorageSync('integral'),
          transferName:basic_info.plugin_setting.love?.transfer,
        })
      }
    } catch (error) {

    }
  },
  makeTransfer(e) {
    if (e.currentTarget.dataset.url == 'donate') {
      wx.navigateTo({
        url: '/packageB/member/love/love_transfer/love_transfer?key=donate'
      });
      return;
    }
    let urlStr = app.getNetAddresss("plugin.love.Frontend.Controllers.page.authentication");
    app._getNetWork({
      url: urlStr,
      success: (response) => {

        if (response.data.result === 1) {

          if (response.data.data.flag) {
            wx.navigateTo({
              url: '/packageB/member/love/love_transfer/love_transfer'
            });
          } else {
            app.tips(response.data.msg);
          }
        } else {
          app.tips(response.data.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  // 海报
  tapPoster() {
    var that = this;
    let urlStr = app.getNetAddresss("plugin.love.Frontend.Controllers.poster");
    app._postNetWork({
      url: urlStr,
      success: (res) => {
        let resdata = res.data.data;
        if (res.data.result === 1) {
          that.setData({
            posterImg: resdata,
            showPoster: true
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  onPosterClose() {
    this.setData({
      showPoster: false
    });
  },
  saveImg() {
    wx.previewImage({
      current: this.data.posterImg, // 当前显示图片的http链接
      urls: [this.data.posterImg] // 需要预览的图片http链接列表
    });
  },
  getBalance() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.love.Frontend.Controllers.page.index");
    app._getNetWork({
      url: urlStr,
      success: (response) => {
        let resData = response.data;
        let mailLanguage = wx.getStorageSync("mailLanguage");
        if (mailLanguage && resData.data.withdraw_date) {
          mailLanguage = JSON.parse(mailLanguage);
          resData.data.withdraw_date.language = mailLanguage.income.name_of_withdrawal;
        }
        if (resData.result === 1) {
          if (resData.data.withdraw_date) {
            this.setData({
              withdrawData: resData.data.withdraw_date
            });
          }
          console.log(resData.data.love_queue, 'sssssssss');
          this.setData({
            transfer_point_status: resData.data.transfer_point_status,
            pointKey: resData.data.point_name,
            froze: resData.data.froze,
            love_name: resData.data.love_name,
            title: resData.data.love_name,
            usable: resData.data.usable,
            transfer_status: resData.data.transfer_status,
            trading_status: resData.data.trading_set.trading,
            no_recharge: resData.data.no_recharge,
            withdraw_status: resData.data.withdraw_status,
            recharge_status: resData.data.recharge_status,
            froze_name: resData.data.froze_name,
            usable_name: resData.data.usable_name,
            redpack_enable: resData.data.redpack_enable,
            activation_record: resData.data.activation_record,
            poster_center_show: resData.data.poster_center_show,
            love_poster_name: resData.data.love_poster_name,
            love_cycle_reward: resData.data.love_cycle_reward,
            speed_pool_enable:resData.data.speed_pool_enable,
            change_integral:resData.data.change_integral || {},
            active_froze:resData.data.active_froze,
            show_usable : resData.data.show_usable,
            transformation_point:resData.data.transformation_point,
            usable_love_to_freeze:resData.data.usable_love_to_freeze
          });
          if (resData.data.love_queue) {
            this.setData({
              'love_queue.credit_validity_at': app.getTimeDifference(JSON.parse(JSON.stringify(resData.data.love_queue.credit_validity_at))),
              love_queue: resData.data.love_queue !== undefined ? JSON.parse(JSON.stringify(resData.data.love_queue)) : '',
              love_queue_length: resData.data.love_queue !== undefined ? String(resData.data.love_queue.queue_credit).length : 0,
            });
          }
          wx.setNavigationBarTitle({
            title: that.data.title,
          });
          wx.setStorageSync('love_name', that.data.love_name);
          if (that.data.trading_status == 1) {
            that.getLove();
          }

        } else {
          wx.showToast({
            title: resData.msg,
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });

  },
  gotoPage(e) {
    var url = e.target.dataset.url || e.currentTarget.dataset.url;
    if (url === "loveWithdrawals") {
      if (this.data.withdrawData.disable == 1) {
        wx.showToast({
          icon: "none",
          title: this.data.withdrawData.day_msg
        });
        return;
      }
    }
    if (url == 'LoveRecharge' && this.data.ios_virtual_pay) {
      wx.showModal({
        title: '提示',
        content: '十分抱歉，由于相关规定，你暂时无法在这里充值！',
        confirmText: '知道了',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log(res);
          }
        }
      });
      return false;
    }
    if (url == 'love_trading_sell') {

      // this.setData({
      //   show: true
      // });
      // wx.setNavigationBarTitle({
      //   title: `${this.data.love_name}出售`
      // });
      wx.navigateTo({
        url: '/packageA/member/balance/transformLoveV/transformLoveV?name=transformLoveV',
      })
      return;
    }
    if (url == 'loveCycleReceive') {
      wx.navigateTo({
        url: '/packageB/member/love/' + url + '/' + url + '?love_name=' + this.data.love_name
      });
      return;
    }
    if (url == "LoveSpeedLease") {
      return wx.navigateTo({
        url: `/packageB/member/love/${url}/${url}?love_name=${this.data.love_name}`,
      })
    }
    if (url == "love_active_froze") {
      return wx.navigateTo({
        url: `/packageB/member/love/${url}/${url}?froze_name=${this.data.froze_name}&pointKey=${this.data.pointKey}`,
      })
    }
    if (url == 'toIntegral') {
      let time = new Date().getTime();
      let {
        start,
        end
      } = this.data.change_integral;
      let starttime = new Date(start.replace(/-/g, '/')).getTime();
      let endtime = new Date(end.replace(/-/g, '/')).getTime();
      if (starttime > time || time > endtime) {
        // wx.showToast({
        //   title: `当前不能转换\n请在${start}到${end}转换`,
        //   icon: 'none'
        // })
        wx.showToast({
          title: `请在${start}到${end}转换`,
          icon: 'none'
        })
        return
      }
    }
    if(url == "toPoint"){
      wx.navigateTo({
        url: '/packageB/member/love/toIntegral/toIntegral?name=point'
      });
      return
    }
    if(url == "toFreeze"){
      wx.navigateTo({
        url: '/packageB/member/love/toIntegral/toIntegral?name=toFreeze'
      });
      return
    }
    wx.navigateTo({
      url: '/packageB/member/love/' + url + '/' + url
    });
  },
  // 爱心值出售的方法
  // getUsable() {
  //   let urlStr = app.getNetAddresss("plugin.love.Frontend.Controllers.page.index");
  //   app._postNetWork({
  //     url: urlStr,
  //     success: (res) => {
  //       if (res.data.result === 1) {
  //         this.setData({
  //           usable: res.data.data.usable
  //         });
  //       } else {
  //         wx.showToast({
  //           title: res.data.msg
  //         });
  //       }
  //     },
  //     fail: function(res) {
  //       console.log(res);
  //     }
  //   });
  // },
  getLove() {
    var that = this;
    let urlStr = app.getNetAddresss("plugin.love.Frontend.Modules.Trading.Controllers.trading.get-sell-love");
    app._postNetWork({
      url: urlStr,
      success: (res) => {
        if (res.data.result === 1) {
          if (res.data.data.love == null) {
            this.setData({
              usables: 0,
              poundage: res.data.data.set.poundage,
              trading_limit: res.data.data.set.trading_limit,
              trading_fold: res.data.data.set.trading_fold
            });
          } else {
            this.setData({
              usables: res.data.data.love.usable,
              poundage: res.data.data.set.poundage,
              trading_limit: res.data.data.set.trading_limit,
              trading_fold: res.data.data.set.trading_fold
            });
          }
          try {
            if (!app._isTextEmpty(res.data.data.set.trading_fetter)) {
              that.setData({
                trading_fetter: res.data.data.set.trading_fetter
              });
            }
          } catch (err) {
            console.log(err);
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  saleBalance() {

    if (!this.data.sell_value) {
      wx.showToast({
        title: "请输入您要出售的数额",
        icon: 'none'
      });
      return;
    }
    let urlStr = app.getNetAddresss("plugin.love.Frontend.Modules.Trading.Controllers.trading.save-sell-love");
    urlStr += "&amount=" + this.data.sell_value;
    app._postNetWork({
      url: urlStr,
      success: (res) => {
        if (res.data.result === 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
          this.setData({
            sell_value: ""
          });
          setTimeout(() => {
            this.getLove();
            this.onClickLeft();
          }, 1000);
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  // 输入框改变的时候触发
  onChange(val) {
    this.setData({
      sell_value: val.detail
    });
  },
  // 左侧标题被点击时
  onClickLeft() {
    this.setData({
      show: false
    });
    wx.setNavigationBarTitle({
      title: this.data.title,
    });
  },
  onClickRight() {
    wx.navigateTo({
      url: "/packageB/member/love/love_list/love_list"
    });
  },
});